Golang : Setting variable value with ldflags
This short tutorial will demonstrate how to initialize a variable value during runtime at the stage of compilation/linking. Go linker has an option to set the value of an uninitialised string variable:
-X symbol value
Set the value of an otherwise uninitialized string variable.
The symbol name should be of the form importpath.name,
as displayed in the symbol table printed by "go tool nm".
For example :
package main
import "fmt"
var str string
func main() {
fmt.Println(str)
}
and execute the program with -ldflags
to initialize the str variable value
$ go run -ldflags "-X main.str abc" main.go
or if you prefer, build it first into executable binary :
$ go build -ldflags "-X main.str 'abc'" main.go && ./main
Output :
abc
Reference :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9k Golang : automatically figure out array length(size) with three dots
+7.5k Golang : Hue, Saturation and Value(HSV) with OpenCV example
+30.4k Golang : How to redirect to new page with net/http?
+5.7k Golang : Frobnicate or tweaking a string example
+18k Golang : How to make a file read only and set it to writable again?
+21.2k Golang : Get password from console input without echo or masked
+4.8k PHP : Extract part of a string starting from the middle
+7.2k Golang : Array mapping with Interface
+11.8k Golang : How to detect a server/machine network interface capabilities?
+7.4k Golang : Calculate how many weeks left to go in a given year
+5.4k Golang : fmt.Println prints out empty data from struct